'use client';

import { useSyncStatus } from '@/hooks/useSyncStatus';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { RefreshCw, Activity, AlertTriangle, CheckCircle, XCircle, Clock } from 'lucide-react';

interface StatusIndicatorProps {
  status: 'healthy' | 'warning' | 'error' | 'unknown';
  children: React.ReactNode;
}

const StatusIndicator = ({ status, children }: StatusIndicatorProps) => {
  const getStatusColor = () => {
    switch (status) {
      case 'healthy': return 'text-green-600';
      case 'warning': return 'text-yellow-600';
      case 'error': return 'text-red-600';
      default: return 'text-gray-600';
    }
  };

  const getStatusIcon = () => {
    switch (status) {
      case 'healthy': return <CheckCircle className="w-4 h-4" />;
      case 'warning': return <AlertTriangle className="w-4 h-4" />;
      case 'error': return <XCircle className="w-4 h-4" />;
      default: return <Clock className="w-4 h-4" />;
    }
  };

  return (
    <div className={`flex items-center gap-2 ${getStatusColor()}`}>
      {getStatusIcon()}
      {children}
    </div>
  );
};

interface ProgressBarProps {
  percentage: number;
  className?: string;
}

const ProgressBar = ({ percentage, className = '' }: ProgressBarProps) => {
  const getProgressColor = () => {
    if (percentage >= 95) return 'bg-green-500';
    if (percentage >= 80) return 'bg-yellow-500';
    return 'bg-red-500';
  };

  return (
    <div className={`w-full bg-gray-200 rounded-full h-2 ${className}`}>
      <div
        className={`h-2 rounded-full transition-all duration-300 ${getProgressColor()}`}
        style={{ width: `${Math.min(percentage, 100)}%` }}
      />
    </div>
  );
};

export const SyncStatus = () => {
  const { 
    syncStatus, 
    eventStats, 
    blockchainStats, 
    syncProgress, 
    healthStatus, 
    loading, 
    error, 
    lastUpdated, 
    refresh 
  } = useSyncStatus();

  if (loading && !syncStatus) {
    return (
      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="w-5 h-5" />
            區塊鏈同步狀態
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-8">
            <RefreshCw className="w-6 h-6 animate-spin" />
            <span className="ml-2">載入中...</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error && !syncStatus) {
    return (
      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="w-5 h-5" />
            區塊鏈同步狀態
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-red-600 text-center py-4">
            <XCircle className="w-8 h-8 mx-auto mb-2" />
            <p>無法載入同步狀態</p>
            <p className="text-sm text-gray-600 mt-1">{error}</p>
            <Button 
              onClick={refresh} 
              variant="outline" 
              size="sm" 
              className="mt-3"
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              重試
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Activity className="w-5 h-5" />
              區塊鏈同步狀態
            </CardTitle>
            <CardDescription>
              {lastUpdated && `最後更新: ${lastUpdated.toLocaleTimeString('zh-TW')}`}
            </CardDescription>
          </div>
          <Button
            onClick={refresh}
            variant="outline"
            size="sm"
            disabled={loading}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            刷新
          </Button>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 整體健康狀態 */}
        <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
          <div>
            <h3 className="font-semibold text-lg">整體狀態</h3>
            <StatusIndicator status={healthStatus as 'healthy' | 'warning' | 'error' | 'unknown'}>
              <span className="font-medium">
                {healthStatus === 'healthy' && '運行正常'}
                {healthStatus === 'warning' && '注意警告'}
                {healthStatus === 'error' && '錯誤狀態'}
                {healthStatus === 'unknown' && '狀態未知'}
              </span>
            </StatusIndicator>
          </div>
        </div>

        {/* 區塊鏈連接狀態 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <h4 className="font-semibold text-md">區塊鏈連接</h4>
            <StatusIndicator status={syncStatus?.blockchain?.connected ? 'healthy' : 'error'}>
              <span>{syncStatus?.blockchain?.connected ? '已連接' : '連接失敗'}</span>
            </StatusIndicator>
            {syncStatus?.blockchain?.connected && (
              <div className="text-sm text-gray-600 space-y-1">
                <p>網路: {syncStatus.blockchain.network_name} ({syncStatus.blockchain.network})</p>
                <p>最新區塊: #{syncStatus.blockchain.latest_block?.toLocaleString()}</p>
                <p>Chain ID: {syncStatus.blockchain.chain_id}</p>
              </div>
            )}
          </div>

          <div className="space-y-2">
            <h4 className="font-semibold text-md">事件監聽</h4>
            <StatusIndicator status={syncStatus?.monitoring?.is_active ? 'healthy' : 'error'}>
              <span>{syncStatus?.monitoring?.is_active ? '監聽中' : '已停止'}</span>
            </StatusIndicator>
            {syncStatus?.monitoring?.contracts_initialized && (
              <p className="text-sm text-gray-600">合約已初始化</p>
            )}
          </div>
        </div>

        {/* 背景任務狀態 */}
        <div className="space-y-3">
          <h4 className="font-semibold text-md">背景任務</h4>
          <div className="flex items-center justify-between">
            <StatusIndicator status={syncStatus?.background_tasks?.is_running ? 'healthy' : 'error'}>
              <span>
                {syncStatus?.background_tasks?.is_running ? '運行中' : '已停止'} 
                ({syncStatus?.background_tasks?.task_count || 0} 個任務)
              </span>
            </StatusIndicator>
          </div>
          
          {syncStatus?.background_tasks?.tasks && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
              {Object.entries(syncStatus.background_tasks.tasks).map(([taskName, taskStatus]) => (
                <div key={taskName} className="flex items-center gap-2">
                  <StatusIndicator 
                    status={
                      taskStatus.exception ? 'error' : 
                      taskStatus.cancelled ? 'warning' : 
                      taskStatus.done ? 'warning' : 'healthy'
                    }
                  >
                    <span className="capitalize">
                      {taskName.replace(/_/g, ' ')}
                    </span>
                  </StatusIndicator>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 事件同步進度 */}
        {syncProgress && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="font-semibold text-md">事件同步進度</h4>
              <span className="text-sm font-medium">{syncProgress.percentage}%</span>
            </div>
            <ProgressBar percentage={syncProgress.percentage} />
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div className="text-center">
                <p className="text-gray-600">總計</p>
                <p className="font-semibold">{syncProgress.total.toLocaleString()}</p>
              </div>
              <div className="text-center">
                <p className="text-gray-600">已處理</p>
                <p className="font-semibold text-green-600">{syncProgress.processed.toLocaleString()}</p>
              </div>
              <div className="text-center">
                <p className="text-gray-600">待處理</p>
                <p className="font-semibold text-yellow-600">{syncProgress.pending.toLocaleString()}</p>
              </div>
              <div className="text-center">
                <p className="text-gray-600">失敗</p>
                <p className="font-semibold text-red-600">{syncProgress.failed.toLocaleString()}</p>
              </div>
            </div>
          </div>
        )}

        {/* 事件類型統計 */}
        {eventStats?.event_types && Object.keys(eventStats.event_types).length > 0 && (
          <div className="space-y-3">
            <h4 className="font-semibold text-md">事件類型分佈</h4>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2 text-sm">
              {Object.entries(eventStats.event_types).map(([eventType, count]) => (
                <div key={eventType} className="flex justify-between p-2 bg-gray-50 rounded">
                  <span>{eventType}</span>
                  <span className="font-medium">{count.toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 合約監聽統計 */}
        {eventStats?.contracts && Object.keys(eventStats.contracts).length > 0 && (
          <div className="space-y-3">
            <h4 className="font-semibold text-md">合約事件統計</h4>
            <div className="space-y-2 text-sm">
              {Object.entries(eventStats.contracts).map(([contract, count]) => (
                <div key={contract} className="flex justify-between p-2 bg-gray-50 rounded">
                  <span className="font-mono text-xs">{contract}</span>
                  <span className="font-medium">{count.toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
};